package com.zr.bookcorner.websocket;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.lurencun.service.autoupdate.AppUpdate;
import com.lurencun.service.autoupdate.AppUpdateService;
import com.lurencun.service.autoupdate.Version;
import com.lurencun.service.autoupdate.send.UpdateConstant;
import com.zh.baselibrary.constant.BaseConstant;
import com.zh.baselibrary.constant.ExtraName;
import com.zh.baselibrary.netutils.BaseResp;
import com.zh.baselibrary.netutils.HRetrofitNetHelper;
import com.zh.baselibrary.utils.FileUtils;
import com.zh.baselibrary.utils.JsonUtils;
import com.zh.baselibrary.utils.LogUtils;
import com.zh.baselibrary.utils.ShareManager;
import com.zh.model.cabinet.UserInfo;
import com.zh.model.home.FirstLoginInfo;
import com.zr.bookcorner.activity.LimitActivity;
import com.zr.bookcorner.constant.Constant;
import com.zr.bookcorner.service.HeartService;
import com.zr.bookcorner.utils.ImageDownAsyncTask;
import com.zr.websocket.ErrorResponse;
import com.zr.websocket.IResponseDispatcher;
import com.zr.websocket.Response;
import com.zr.websocket.ResponseDelivery;

/**
 * Created by ZhangKe on 2018/6/27.
 */
public class AppResponseDispatcher implements IResponseDispatcher {

    private static final String LOGTAG = "AppResponseDispatcher";

    private Context mContext;

    public AppResponseDispatcher(Context context) {

        this.mContext = context;
    }

    @Override
    public void onConnected(ResponseDelivery delivery) {
        delivery.onConnected();
    }

    @Override
    public void onConnectError(Throwable cause, ResponseDelivery delivery) {
        delivery.onConnectError(cause);
    }

    @Override
    public void onDisconnected(ResponseDelivery delivery) {
        delivery.onDisconnected();
    }

    /**
     * 统一处理响应的数据
     * 首次登录：1
     * 授权时间更改：2
     * 应用更新（升级）：3
     * 扫码登录：4
     * 设备信息更新：5
     * 锁定、解锁：6
     */
    @Override
    public void onMessageResponse(Response message, ResponseDelivery delivery) {
        try {

            Gson mGson = new Gson();


            BaseResp baseResp = mGson.fromJson(message.getResponseText(), BaseResp.class);
            LogUtils.e(JsonUtils.objectToString(baseResp));
            if (baseResp.isSuccess()) {
                JsonElement je = new JsonParser().parse(message.getResponseText());
                System.out.println(je.isJsonObject());
                JsonElement actionObject = je.getAsJsonObject().get("data").getAsJsonObject().get("action");
                Integer action = actionObject.getAsInt();
                if (action == 1) {
                    //首次登录
                    JsonElement equipment = je.getAsJsonObject().get("data").getAsJsonObject().get("equipmentInfo");
                    FirstLoginInfo info = mGson.fromJson(equipment.getAsJsonObject(), FirstLoginInfo.class);

                    ShareManager.setValue(mContext, BaseConstant.AUTHORIZATION_DEADLINE_BOOK, info.getAuthorizationTime());
                    ShareManager.setValue(mContext, BaseConstant.DEVICE_SCHOOL_ID, info.getSchoolId() + "");
                    ShareManager.setValue(mContext, BaseConstant.DEVICE_SCHOOL_NAME, info.getSchoolName() + "");
                    ShareManager.setLong(mContext,  BaseConstant.DEVICE_ID, info.getId());
                    ShareManager.setValue(mContext, BaseConstant.DEVICE_LOCATION, info.getLocation());
                    ShareManager.setValue(mContext, BaseConstant.DEVICE_TYPE, info.getType());
                    ShareManager.setInt(mContext, BaseConstant.DEVICE_VOICE, info.getVoiceSwitch());
                    BaseConstant.canSpeak = info.getVoiceSwitch() == 1;
                    sendBroatCast(BaseConstant.BROAT_CAST_ACTION_FIRST_LOGIN, null);

                } else if (action == 2) {
                    //授权时间更改
                    JsonElement deadLine = je.getAsJsonObject().get("data").getAsJsonObject().get("authorizationTime");
                    Long deadLineL = deadLine.getAsLong();
                    if (deadLineL <= System.currentTimeMillis()) {
                        Intent mIntent = new Intent(mContext, LimitActivity.class);
                        mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        mIntent.putExtra(ExtraName.KEY_DATA, 1);
                        mContext.startActivity(mIntent);
                    }
                    ShareManager.setLong(mContext, BaseConstant.AUTHORIZATION_DEADLINE_BOOK, deadLineL);
                } else if (action == 3) {
                    //应用更新（升级）
                    JsonElement versionJson = je.getAsJsonObject().get("data").getAsJsonObject().get("version");
                    AppUpdate appUpdate = AppUpdateService.getAppUpdate(mContext);
                    Version version = mGson.fromJson(versionJson.getAsJsonObject(), Version.class);
                    version.targetUrl = HRetrofitNetHelper.getDownloadUrl() + version.targetUrl;
                    appUpdate.downloadAndInstall(version);
                } else if (action == 4) {
                    //扫码登录
                    JsonElement userObject = je.getAsJsonObject().get("data").getAsJsonObject().get("user");

                    UserInfo info = mGson.fromJson(userObject.getAsJsonObject(), UserInfo.class);

                    ShareManager.setValue(mContext, BaseConstant.TOKEN_ID, info.getToken());
                    sendBroatCast(Constant.BROAT_CAST_ACTION_QRCODE_LOGIN, null);

                } else if (action == 5) {
                    //设备信息更新
                    JsonElement equipment = je.getAsJsonObject().get("data").getAsJsonObject().get("equipmentInfo");
                    FirstLoginInfo info = mGson.fromJson(equipment.getAsJsonObject(), FirstLoginInfo.class);

                    ShareManager.setValue(mContext, BaseConstant.AUTHORIZATION_DEADLINE_BOOK, info.getAuthorizationTime());
                    ShareManager.setValue(mContext, BaseConstant.DEVICE_SCHOOL_ID, info.getSchoolId() + "");
                    ShareManager.setLong(mContext, BaseConstant.DEVICE_ID, info.getId());
                    ShareManager.setValue(mContext, BaseConstant.DEVICE_SCHOOL_NAME, info.getSchoolName());
                    ShareManager.setValue(mContext, BaseConstant.DEVICE_LOCATION, info.getLocation());
                    ShareManager.setValue(mContext, BaseConstant.DEVICE_TYPE, info.getType());
                    ShareManager.setInt(mContext, BaseConstant.DEVICE_VOICE, info.getVoiceSwitch());
                    BaseConstant.canSpeak = info.getVoiceSwitch() == 1;
                    sendBroatCast(BaseConstant.BROAT_CAST_ACTION_EQUIPMENT_UPDATE, null);
                } else if (action == 6) {
                    //锁定解锁
                    JsonElement userObject = je.getAsJsonObject().get("data").getAsJsonObject().get("type");
                    //0 锁定1解锁
                    int type = userObject.getAsInt();
                    ShareManager.setInt(mContext, BaseConstant.DEVICE_LOCK_TYPE, type + 1);
                    if (type == 0) {
                        Intent mIntent = new Intent(mContext, LimitActivity.class);
                        mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        mIntent.putExtra(ExtraName.KEY_DATA, 2);
                        mContext.startActivity(mIntent);
                    } else {
                        sendBroatCast(BaseConstant.BROAT_CAST_ACTION_UN_LOCK, 2 + "");
                    }


                } else if (action == 7) {
                    //轮播图
                    JsonElement urlJson = je.getAsJsonObject().get("data").getAsJsonObject().get("data");
                    JsonArray urlJsonArray = urlJson.getAsJsonArray();
                    //删除本地文件
                    try {
                        FileUtils.deleteFolder(Environment.getExternalStorageDirectory() + ImageDownAsyncTask.PATH);
                    } catch (Exception e) {

                    }
                    if (urlJsonArray.size() != 0) {
                        for (JsonElement jsonElement : urlJsonArray) {
                            String url = jsonElement.getAsString();
                            new ImageDownAsyncTask().execute(HRetrofitNetHelper.getDownloadUrl() + url);
                        }
                    }

                    sendBroatCast(Constant.BROAT_CAST_ACTION_BARNER, null);


                }
            }
        } catch (Exception e) {
            System.out.println("websocket 解析异常 数据--》 " + message.getResponseText());

        }

    }


    public void sendBroatCast(String action, String value) {
        Intent mIntent = new Intent();
        if (!TextUtils.isEmpty(value)) {
            mIntent.putExtra(ExtraName.KEY_DATA, value);
        }
        mIntent.setAction(action);
        mContext.sendBroadcast(mIntent);
    }

    /**
     * 统一处理错误信息，
     * 界面上可使用 ErrorResponse#getDescription() 来当做提示语
     */
    @Override
    public void onSendMessageError(ErrorResponse error, ResponseDelivery delivery) {
        switch (error.getErrorCode()) {
            case 1:
                error.setDescription("网络错误");
                break;
            case 2:
                error.setDescription("网络错误");
                break;
            case 3:
                error.setDescription("网络错误");
                break;
            case 11:
                error.setDescription("数据格式异常");
                Log.e(LOGTAG, "数据格式异常", error.getCause());
                break;
        }
        delivery.onSendMessageError(error);
    }
}
